var paginationIndex = 6;
var u_index = 0;
var totalPostNo = 0;
var startEnds;

var getUrlVars = function() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
			function(m, key, value) {
				vars[key] = value;
			});
	return vars;
}

var submitMoods = function(mood, moodType) {
	$.ajax({
		type : "POST",
		url : 'seabookchen/mood',
		cache : false,
		data : {
			mood : mood,
			moodType : moodType
		},
		success : function(data) {
			$('#moods-action').fadeIn(1000).html(data).fadeOut(5000,
					function() {
						getAllMoods(5);
					});
		}
	});
}

var getAllMoods = function(index) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/allmoods/' + index,
		cache : false,
		beforeSend : function() {
			$('#loading-moods').show();
		},
		complete : function() {
			$('#loading-moods').hide();
		},
		success : function(data) {
			$('#showMoods').html(data);
		}

	});
}

var submitNews = function(news) {
	$.ajax({
		type : "POST",
		url : 'seabookchen/news',
		cache : false,
		data : {
			news : news
		},
		success : function(data) {
			$('#news-action').fadeIn(1000).html(data).fadeOut(5000, function() {
				getAllNews(5);
			});
		}
	});
}

var getAllNews = function(index) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/allnews/' + index,
		cache : false,
		beforeSend : function() {
			$('#loading-news').show();
		},
		complete : function() {
			$('#loading-news').hide();
		},
		success : function(data) {
			$('#showNews').html(data);
		}
	});
}

var submitPost = function(title, content, tags) {
	$.ajax({
		type : "POST",
		url : 'seabookchen/blogpost',
		cache : false,
		data : {
			title : title,
			content : content,
			tags : tags
		},
		success : function(data) {
			$('.post-success').fadeIn(1000).html('Post is created!!!').fadeOut(
					5000);
		}
	});
}

var submitTag = function(tag) {
	$.ajax({
		type : "POST",
		url : 'seabookchen/tag',
		cache : false,
		data : {
			tag : tag
		},
		success : function(data) {
			$('.post-success').fadeIn(1000).html('Tag is created!!!').fadeOut(
					5000);
		}
	});
}

var fetchBlogPosts = function(from, to, elemId) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/listposts/range',
		cache : false,
		beforeSend : function() {
			$('#loading-blogposts').show();
		},
		complete : function() {
			$('#loading-blogposts').hide();
		},
		data : {
			start : from,
			end : to
		},
		success : function(data) {
			$(elemId).html(data);
		}
	});
}

var fetchBlogPost = function(id) {
	var jsonResult = undefined;
	$.ajax({
		type : "GET",
		url : 'seabookchen/blogpost/' + id + ".json",
		dataType : 'json',
		async : false,
		cache : false,
		success : function(data) {
			jsonResult = data;
		}
	});
	return jsonResult;
}

var fetchBlogPostById = function(elemId) {
	var id = getUrlVars()['blogId'];
	$.ajax({
		type : "GET",
		url : 'seabookchen/blogpost/' + id,
		cache : false,
		beforeSend : function() {
			$('#loading').show();
		},
		complete : function() {
			$('#loading').hide();
			$('body').load(prettyPrint());
			if (stButtons) { 
				var switchTo5x=true;
				stButtons.locateElements();
				stLight.options({publisher: "48c51c05-202e-43ac-b730-9405b592f9ff"});
			}
			
		},
		success : function(data) {
			$(elemId).html(data);
		}
	});
}

var fetchBlogPostByTag = function(elemId, tagId) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/blogpost/posts/tag/' + tagId,
		cache : false,
		beforeSend : function() {
			$('#loading-blogposts').show();
		},
		complete : function() {
			$('#loading-blogposts').hide();
		},
		success : function(data) {
			$(elemId).html(data);
		}
	});
}

var updateBlogPost = function(id, title, content, tags) {
	$.ajax({
		type : "PUT",
		url : 'seabookchen/blogpost/' + id,
		data : {
			title : title,
			content : content,
			tags : tags
		},
		cache : false,
		success : function(data) {
			$('.post-action').fadeIn(1000).html('Post Updated Successful!!!')
					.fadeOut(5000);
		}
	});
}

var fetchBlogPostsFromRange = function() {
	var index = getUrlVars()['index'];
	if (index === undefined || index.trim() === "") {
		u_index = index = '0';
	} else
		u_index = index;

	startEnds = getStartAndEndPoint();
	var pair = startEnds[index];

	var start = pair.start;
	var end = pair.end;

	fetchBlogPosts(start, end, '#fetch-blog-posts');
}

var fetchTags = function() {
	$.ajax({
		type : "GET",
		url : 'seabookchen/alltags',
		cache : false,
		success : function(data) {
			$('#tags').html(data);
		}
	});
}

var fetchTagsJson = function(id, composeHtml) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/alltags.json',
		dataType : 'json',
		cache : false,
		success : function(data) {
			var htmlOutpt = composeHtml(data);
			$(id).html(htmlOutpt);
		}
	});
}

var composeTagList = function(data) {
	var htmlOutpt = '';
	var htmlPlaceholder = '<li><a href="javascript:fetchBlogPostByTag(\'#fetch-blog-posts\', ${ph0})">${ph1}</a></li>';
	for ( var i = 0; i < data.length; i++) {
		var afterReplace = htmlPlaceholder.replace('${ph0}', data[i].id);
		afterReplace = afterReplace.replace('${ph1}', data[i].tag);
		htmlOutpt += afterReplace;
	}
	return htmlOutpt;
}

var fetchTagsWithPostJson = function() {
	$.ajax({
		type : "GET",
		url : 'seabookchen/blogpost/' + id + '/tags.json',
		dataType : 'json',
		cache : false,
		success : function(data) {
			$('#tags').html(data);
		}
	});
}

var fetchTagsAssociatedWithPost = function() {
	var id = getUrlVars()['blogId'];
	$.ajax({
		type : "GET",
		url : 'seabookchen/blogpost/' + id + '/tags',
		cache : false,
		success : function(data) {
			$('#tags').html(data);
		}
	});
}

var getLatestBlogPosts = function(index, elemId) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/listposts/creation/' + index,
		cache : false,
		beforeSend : function() {
			$('#loading-posts').show();
		},
		complete : function() {
			$('#loading-posts').hide();
		},
		success : function(data) {
			$(elemId).html(data);
		}
	});
}

var getLatestBlogPostsJson = function(index, elemId, composeHtml) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/listposts/creation/' + index + '.json',
		dataType : 'json',
		cache : false,
		success : function(data) {
			$(elemId).html(composeHtml(data));
		}
	});
}

var blogWithTitleList = function(data) {
	var htmlOutpt = '';
	var htmlPlaceholder = '<li><a href="/blogPost.jsp?blogId=${ph0}">${ph1}</a></li>';
	for ( var i = 0; i < data.length; i++) {
		var afterReplace = htmlPlaceholder.replace('${ph0}', data[i].id);
		afterReplace = afterReplace.replace('${ph1}', data[i].title);
		htmlOutpt += afterReplace;
	}
	return htmlOutpt;
}

var getLatestBlogComments = function(index) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/allcomments/' + index,
		cache : false,
		beforeSend : function() {
			$('#loading-comments').show();
		},
		complete : function() {
			$('#loading-comments').hide();
			$('body').load(prettyPrint());
		},
		success : function(data) {
			$('#latestBlogComments').html(data);
		}
	});
}

var getBlogTotalSize = function() {
	var totalSize = undefined;
	$.ajax({
		type : "GET",
		url : 'seabookchen/blogpost/size.json',
		cache : false,
		async : false,
		dataType : 'json',
		success : function(data) {
			totalSize = data.totalSize;
		}
	});
	if (totalSize) {
		totalPostNo = totalSize;
	}
}

var getStartAndEndPoint = function() {
	var fromTo = function(from, to) {
		return {
			start : from,
			end : to
		}
	}

	getBlogTotalSize();
//	console.info("totalSize: " + totalPostNo);
	var index = Math.floor(totalPostNo / paginationIndex);
	var startEnds = new Array();

	for ( var i = 0; i <= index; i++) {
		if (i == 0) {
			startEnds.push(fromTo(0, paginationIndex - 1))
		} else if (i == index) {
			startEnds.push(fromTo(i * paginationIndex, totalPostNo - 1));
		} else
			startEnds.push(fromTo(i * paginationIndex, (i + 1)
					* paginationIndex - 1));
	}

	return startEnds;
}

// blogpost
var deleteEntity = function(entityType, id, elem) {
	var restUrl = 'seabookchen/' + entityType + '/' + id;
	$.ajax({
		type : "DELETE",
		url : restUrl,
		cache : false,
		success : function(data) {
			$(elem).fadeIn(1000).html(data).fadeOut(5000, function() {
				if (entityType === 'mood')
					getAllMoods(5);
				if (entityType === 'news')
					getAllNews(5);
			});
		}
	});
}

var getUIndexForPagination = function() {
	return u_index;
}

var hasNextOrPrevious = function() {
	//var startEnds = getStartAndEndPoint();
	var index = getUIndexForPagination();
	var totalSize = totalPostNo;
	var hasNext = function() {
		if (totalSize <= paginationIndex) {
			return false;
		}

		var nextIndex = parseInt(index) + 1;
		if (startEnds[nextIndex] === undefined) {
			return false;
		}
		return true;
	}

	var hasPrevious = function() {
		if (index === "0")
			return false;
		return true;
	}

	if (!hasPrevious())
		$('.previous-posts').hide();
	else
		$('.previous-posts').show();

	if (!hasNext())
		$('.next-posts').hide();
	else
		$('.next-posts').show();

}

function startTime() {
	var today = new Date();
	var h = today.getHours();
	var m = today.getMinutes();
	var s = today.getSeconds();
	// add a zero in front of numbers<10
	m = checkTime(m);
	s = checkTime(s);
	var time = "<font color='red'>**</font>&nbsp;" + h + ":" + m + ":" + s;
	document.getElementById('time').innerHTML = time;

	var t = setTimeout(function() {
		startTime()
	}, 500);

	function checkTime(i) {
		if (i < 10) {
			i = "0" + i;
		}
		return i;
	}
}

var buildPostsPopularity = function(elem) {
	$.ajax({
		type : "POST",
		url : "seabookchen/blogpost/buildPopularity",
		cache : false,
		success : function(data) {
			$(elem).fadeIn(1000).html('Build Popularity successful!!!')
					.fadeOut(5000);
		}
	});
}

var fetchPopularPosts = function(index, elem) {
	$.ajax({
		type : "GET",
		url : "seabookchen/blogpost/popular/" + index,
		cache : false,
		success : function(data) {
			$(elem).html(data);
		}
	});
}

/*
 * All comments realted
 */

var fetchCommentsByPostId = function() {
	var id = getUrlVars()['blogId'];
	$.ajax({
		type : "GET",
		url : 'seabookchen/blogpost/' + id + '/comments',
		cache : false,
		beforeSend : function() {
			$('#loading-comments').show();
		},
		complete : function() {
			$('#loading-comments').hide();
			$('body').load(prettyPrint());
		},
		success : function(data) {
			$('#all-comments').html(data);
		}
	});
}

var addComment = function() {
	var postId = getUrlVars()['blogId'];
	var isValid = true;
	var name = $('#c-name').val();
	var email = $('#c-email').val();
	var content = $('#c-text').val();
	if (name === undefined || name.trim() === '') {
		$('#c-name').val('Cannot be empty!');
		$('#c-name').addClass('error');
		isValid = false;
	}
	if (email === undefined || email.trim() === '') {
		$('#c-email').val('Cannot be empty!');
		$('#c-email').addClass('error');
		isValid = false;
	}
	if (content === undefined || content.trim().length < 10) {
		$('#c-text').val('Less than 10 characters treated as a Spam!!!');
		$('#c-text').addClass('error');
		isValid = false;
	}

	if (!isValid) {
		return;
	}

	var url = $('#c-url').val();

	$.ajax({
		type : "POST",
		url : 'seabookchen/blogpost/' + postId + '/comment',
		cache : false,
		data : {
			username : name,
			email : email,
			url : url,
			content : content
		},
		success : function(data) {
			resetCommentForm();
			$('.post-success').fadeIn(1000).html(
					'Thanks for sharing your thoughts!!!').fadeOut(5000,
					function() {
						fetchCommentsByPostId();
					});
		}
	});
}

//javascript:deleteEntity('blogpost', ${entity.id}, '#post-action')
deleteBlogPost = function(postId) {
	$.ajax({
		type : "DELETE",
		url : 'seabookchen/blogpost/' + postId,
		cache : false,
		success : function(data) {
			$('.delete-success').fadeIn(1000).html('Delete Successfully!').fadeOut(5000);
		}
	});
}

deleteComment = function(postId, commentId) {
	$.ajax({
		type : "DELETE",
		url : 'seabookchen/blogpost/' + postId + '/comment/' + commentId,
		cache : false,
		success : function(data) {
			$('.delete-success').fadeIn(1000).html('Delete Successfully!')
					.fadeOut(5000, function() {
						fetchCommentsByPostId();
					});
		}
	});
}

// Wish

var makeWish = function(wish) {
	$.ajax({
		type : "POST",
		url : 'seabookchen/wish/',
		cache : false,
		data : {
			wish : wish,
		},
		success : function(data) {
			$('.post-success').fadeIn(1000).html('Make Wish Successful!')
					.fadeOut(5000, function() {
						listWishes(5);
					});
		}
	});
}

var listWishes = function(index) {
	$.ajax({
		type : "GET",
		url : 'seabookchen/allwishes/' + index,
		cache : false,
		beforeSend : function() {
			$('#loading-wishes').show();
		},
		complete : function() {
			$('#loading-wishes').hide();
		},
		success : function(data) {
			$('#latest-wishes').html(data);
		}

	});
}

/* Resume */
var showResume = function() {
	$.ajax({
		type : "GET",
		url : 'seabookchen/resume/profile',
		cache : false,
		beforeSend : function() {
			$('#loading-resume').show();
		},
		complete : function() {
			$('#loading-resume').hide();
		},
		success : function(data) {
			$('#resume').html(data);
		}

	});
}

var initProfile = function() {
	$.ajax({
		type : "POST",
		url : 'seabookchen/resume/initprofile',
		cache : false,
		success : function(data) {
			$('.post-action').fadeIn(1000).html(
					'Init Resume Profile Successful!!!').fadeOut(5000);
		}

	});
}
